package com.smartrobot.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;
import org.jivesoftware.smack.Chat;
import org.springframework.stereotype.Service;

import com.smartrobot.service.DeployService;

@Service
public class DeployServiceImpl implements DeployService {

	public static String DEPLOYER_HOME = "";
	private static Logger log = Logger.getLogger(DeployServiceImpl.class);
	@Override
	public String deploy(String args[],Chat chat) {
		StringBuffer shellPath= new StringBuffer();;
		try {
			shellPath.append(getDeployerPath()).append("/autoDeploy.sh 'deploy'");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return e.getMessage();
		}
		StringBuffer rtn = new StringBuffer("\n");
		BufferedReader reader = null;
		try {
			Process pid = null;
			for (int i = 1; i < args.length; i++) {
				shellPath.append(" '").append(args[i]).append("'");
			}
			log.info("start executeShell " + shellPath.toString());
			chat.sendMessage("start executeShell " + shellPath.toString());
			String[] cmd = { "/bin/bash", "-c",shellPath.toString() };
			pid = Runtime.getRuntime().exec(cmd);
			BufferedInputStream in = new BufferedInputStream(pid.getInputStream());
			reader = new BufferedReader(new InputStreamReader(in));
			String s;
			while ((s = reader.readLine()) != null){
				if(s.toLowerCase().indexOf("usage")>-1){
					rtn.append("Usage: deploy <PR|UT> [Sandglass|...]");
					return rtn.toString();
				}
				chat.sendMessage(s);
			}
			pid.waitFor();
		} catch (Exception ioe) {
			ioe.printStackTrace();
			rtn = new StringBuffer("Deploy faild!");
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
		rtn.append("Command executed!");
		return rtn.toString();		
	}

	/**
	 * @return The directory path of autoDeploy.sh
	 * @throws Exception
	 */
	public static String getDeployerPath() throws Exception {
		if(DeployServiceImpl.DEPLOYER_HOME.equals("")){
			//more .bash_profile
			//export DEPLOYER_HOME=/home/sgut/autobuild
			//PATH=$JAVA_HOME/bin:$PATH
			String shell= "echo $DEPLOYER_HOME";
			BufferedReader reader = null;
			try {
				Process pid = null;
				log.info("start executeShell: " + shell);
				String[] cmd = { "/bin/bash", "-c",shell};
				pid = Runtime.getRuntime().exec(cmd);
				BufferedInputStream in = new BufferedInputStream(pid.getInputStream());
				reader = new BufferedReader(new InputStreamReader(in));
				String s;
				while ((s = reader.readLine()) != null){
					if(!s.trim().equals("")){
						DEPLOYER_HOME=s;
					}
				}
				pid.waitFor();
				log.info("DEPLOYER_HOME="+DEPLOYER_HOME);
				if(DeployServiceImpl.DEPLOYER_HOME.equals("")){
					throw new Exception();
				}

			} catch (Exception ioe) {
				ioe.printStackTrace();
				throw new Exception("Faild to get AutoDeployer path! Make sure the $DEPLOYER_HOME had been configed in OS env.");
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException e1) {
					}
				}
			}
		}
		return DEPLOYER_HOME;
	}
}